/**
 * Created by
 */
window.onload = function (ev) {
    topbar.hide();
};
var statusDetail = "";
var batchIdDetail = "";
var batchIds = [];
var myDate = new Date();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
if (month < 10) {
    month = "0" + month;
}
if (day < 10) {
    day = "0" + day;
}
var _start = myDate.getFullYear() + '-' + month + '-' + day + " 00:00:00";
var _end = myDate.getFullYear() + '-' + month + '-' + day + " 23:59:59";
$("#buyStartTime").val(_start);
$("#buyEndTime").val(_end);
$('.icheck').iCheck({
    checkboxClass: 'icheckbox_square-blue checkbox',
    radioClass: 'iradio_square-blue'
});
$(document).ready(function () {
    $("#successModalForm").validate({
        rules: {
            actualFace: {
                required: true,
            },
        },
        errorClass: "help-inline",
        errorElement: "p",
        highlight: function (element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        }
    });
})
laydate.render({
    elem: '#buyStartTime',
    type: 'datetime'

});
laydate.render({
    elem: '#buyEndTime'
    , type: 'datetime'
});
$.ajax({
    type: "POST",
    url: "/CardProductController/queryAllCardOperatorList",
    dataType: "json",
    async: false,
    success: function (data) {
        $("#operator").html("");
        var str = "<option value=\"\" selected>运营商</option>";
        if (data != null && data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                str += '<option value=' + data[i].cardOperatorId + '>' + data[i].cardOperatorName + '</option>'
            }
        }
        $("#operator").append(str).trigger("chosen:updated");
        ;
    },
    beforeSend: function () {
    }
});
initArea();
var adminRole = roleCheck();
$('#dataTable').bootstrapTable({
    url: '/CardReceiveController/userCardSupplyRecord',
    height: $(window).height() - 200,
    pageSize: 30,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    queryParams: queryParams,
    uniqueId: 'id',
    queryParamsType: '',
    traditional: true,
    sidePagination: 'server',
    showFooter: true,
    responseHandler: function (res) {
        return {
            "total": res.total,//总页数
            "rows": res.resultList   //数据
        };
    }, onClickRow: function (row) {
        if (row.userAccount != null && row.userAccount != '') {
            $("#account_field" + row.batchId).html(row.userAccount);
        }
    },
    columns: [
        {
            checkbox: true
        }, {
            width: '3px',
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        },
        {
            field: 'batchId',
            title: '批次号',
            width: 300,
            align: 'center',
            formatter: function (v, r) {
                return '<a href="javascript:;" onclick=addTab("/batch?batchId="+"' + v + '&startTime="+$("#buyStartTime").val()+"&endTime="+$("#buyEndTime").val(),"1","批次明细")>' + v + '</a>'
            }
        },
        {
            field: 'cardOperatorName',
            title: '运营商',
            width: 50,
            align: 'center'
        },
        {
            field: 'productName',
            title: '产品名称',
            width: 50,
            align: 'center'
        },
        {
            field: 'userAccount', title: '会员编号', width: 90, align: 'center',
            formatter: function (v, r) {
                return copyAddon(v) + (adminRole == 1 ? v : userAccountHidden(r.userAccount, r.batchId));
            }
        },

        {
            field: 'userName', title: '会员名称', width: 90, align: 'center'
        },
        {
            field: 'face', title: '面值', width: 80, align: 'center'
        },

        {
            field: 'userPrice',
            title: '折扣',
            width: 80,
            align: 'center',
            sortable: true,
            formatter: function (v, r) {
                if (r.productType > 310) {
                    return "1";
                } else {
                    return v;
                }
            }
        },
        {
            field: 'area', title: '销卡地区', width: 60, align: 'center',
        },
        {
            field: 'startDate',
            title: '收卡时间',
            width: 130,
            align: 'center',
            footerFormatter: function (value) {
                return "合计";
            }
        },
        {
            field: 'total', title: '收卡数', width: 60, align: 'center', sortable: true,
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].total);
                }
                return count + "";
            }
        },
        {
            field: 'preCount',
            title: '可售数',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",3)'><span style='color:red'>" + v + "</span></a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].preCount);
                }
                return count + "";
            }
        },
        {
            field: 'dealingCount',
            title: '在售数',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",0)'><span style='color:red'>" + v + "</span></a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].dealingCount);
                }
                return count + "";
            }
        },
        {
            field: 'successCount',
            title: '已售数',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",1)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].successCount);
                }
                return count + "";
            }
        },
        {
            field: 'failCount',
            title: '停售数',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",2)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].failCount);
                }
                return count + "";
            }
        },
        {
            field: 'preJudge',
            title: '未预判数',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",4)'><span style='color:red'>" + v + "</span></a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].preJudge);
                }
                return count + "";
            }
        },
        {
            field: 'wrongFace',
            title: '预判不符',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",5)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].wrongFace);
                }
                return count + "";
            }
        }, {
            field: 'waitSettlement',
            title: '待结算',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",9)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].waitSettlement);
                }
                return count + "";
            }
        }, {
            field: 'disputing',
            title: '纠纷中',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",10)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].disputing);
                }
                return count + "";
            }
        },
        {
            field: 'fixCount',
            title: '补结算数',
            width: 60,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",50)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].fixCount);
                }
                return count + "";
            }
        },
        {
            field: 'waitSlowTrySell',
            title: '等待慢速试充',
            width: 80,
            align: 'center',
            formatter: function (v, r) {
                if (v == 0 || r.productType == 999) {
                    return v;
                }
                var s = JSON.stringify(r);
                return "<a href='javascript:void(0)' onclick='jumpTodetail(" + s + ",7)'>" + v + "</a>";
            },
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].waitSlowTrySell);
                }
                return count + "";
            }
        },
        {
            field: 'totalFace', title: '收卡总面值', width: 80, align: 'center',
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].totalFace);
                }
                return count.toFixed(4) + "";
            }
        },
        {
            field: 'settlePrice', title: '已销卡总面值', width: 80, align: 'center',
            footerFormatter: function (value) {
                var count = 0;
                for (var i in value) {
                    count = parseFloat(count) + parseFloat(value[i].settlePrice);
                }
                return count.toFixed(4) + "";
            }
        }
    ]

});

$("#search").click(function () {
    var timeAdd = new Date($("#buyStartTime").val());
    var timeEnd = new Date($("#buyEndTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    var require = (timeEnd - timeAdd) / (1 * 24 * 60 * 60 * 1000);
    if (require > 7) {
        layer.msg("时间间隔不能超过7天");
        return;
    }
    $("#dataTable").bootstrapTable("refresh");
});

function queryParams(params) {
    return {
        productTypeStr: $('#operator').val().join(','),
        statusArrayStr: $('#state').val().join(','),
        userAccount: $.trim($('#name').val()),
        orderId: $.trim($('#orderId').val()),
        page: params.pageNumber,
        size: params.pageSize,
        startTime: $("#buyStartTime").val(),
        endTime: $("#buyEndTime").val(),
        batchId: $.trim($("#batch").val()),
        area: $.trim($("#area").val()),
        face: $.trim($("#faceValue").val()),
        lowDiscount: $.trim($("#count").val()),
        highDiscount: $.trim($("#count1").val()),
        include: $("#include").val(),
    };
}

function batchFailFun() {
    batchIds = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的订单");
        return;
    }
    for (var i = 0; i < rows.length; i++) {
        batchIds.push(rows[i].batchId);
    }
    $("#failModal").modal("show");
}

$("#failBtn").click(function () {
    $.ajax({
        type: "POST",
        url: "/CardReceiveController/setBatchFail",
        traditional: true,
        data: {
            batchIds: batchIds,
            status: $("input[name='status']:checked").val(),
        },
        dataType: "json",
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                layer.msg(data.message);
                $("#failModal").modal("hide");
            } else {
                layer.msg(data.message)
            }
        },
        beforeSend: function () {
        }
    });
})

$("#dataTable1").bootstrapTable({
    url: '/CardReceiveController/cardDetailByBatchId',
    pageSize: 100,
    pagination: true,
    pageList: [30, 50, 80, 100],
    clickToSelect: true,
    queryParams: queryParamsDetail,
    uniqueId: 'id',
    queryParamsType: '',
    sidePagination: 'server',
    responseHandler: function (res) {
        return {
            "total": res.total,//总页数
            "rows": res.resultList   //数据
        };
    },
    columns: [[
        {
            width: '40px',
            align: 'center',
            field: 'cardNumber',
            title: '卡号'
        }, {
            width: '40px',
            align: 'center',
            field: 'startTime',
            title: '收卡时间'
        }, {
            width: '40px',
            align: 'center',
            field: 'endTime',
            title: '销卡时间'
        }, {
            field: 'timeElapse',
            title: '销卡耗时(秒)',
            width: 75,
            align: 'center',
            formatter: function (v, o) {
                if (o.status == 1) {
                    return (new Date(o.endTime).getTime() - new Date(o.startTime).getTime()) / 1000
                } else {
                    return '--';
                }
            }
        }, {
            width: '40px',
            align: 'center',
            field: 'userPrice',
            title: '折扣'
        }, {
            width: '40px',
            align: 'center',
            field: 'face',
            title: '收卡面值'
        }, {
            width: '40px',
            align: 'center',
            field: 'settlePrice',
            title: '已销卡面值'
        }, {
            width: '40px',
            align: 'center',
            field: 'judgeFace',
            title: '预判面值'
        }, {
            width: '40px',
            align: 'center',
            field: 'failExplian'
            /**
            field: 'failReason',
            title: '备注',
            formatter: function (v, o) {
                if (/^[0-9]+$/.test(v)) {
                    return _getCardFailReason(v);
                } else {
                    return v;
                }
            }
            */
        }
    ]]
})

function queryParamsDetail(params) {
    return {
        page: params.pageNumber,
        size: params.pageSize,
        startTime: $("#buyStartTime").val(),
        endTime: $("#buyEndTime").val(),
        batchId: batchIdDetail,
        productTypes: $('#operator').val(),
        status: statusDetail
    };
}

function jumpTodetail(v, s) {
    statusDetail = s;
    batchIdDetail = v.batchId;
    $("#detailModalLabel").html(batchIdDetail + v.area + convertStatus(statusDetail));
    $("#dataTable1").bootstrapTable("refresh");
    $("#detailModal").modal("show")
}
